package by.epam.trenings.vkphotorest.response.common;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Field;
import java.util.concurrent.Executor;

import by.epam.trenings.vkphotorest.http.HttpManager;
import android.os.AsyncTask;

public abstract class CommonAsyncTask<T> extends
		AsyncTask<java.lang.String, java.lang.Void, T> {

	private CallbackAsyncTask<T> mParamCallback;

	public CommonAsyncTask(CallbackAsyncTask<T> paramCallback) {
		super();
		this.mParamCallback = paramCallback;
	}

	private Exception e;

	@SuppressWarnings("unchecked")
	protected T doInBackground(String... params) {

		try {
			String source = HttpManager.getInstance().loadAsString(params[0]);
			mParamCallback.onSuccess((T) source);
		} catch (Exception e) {
			this.e = e;
		}
		return null;
	}

	@Override
	protected void onPostExecute(T result) {
		super.onPostExecute(result);
		if (e != null) {
			mParamCallback.onError(e);
		}
	}

	public void start(String... params) {
		if (android.os.Build.VERSION.SDK_INT > 10) {
			try {
				Method method = android.os.AsyncTask.class.getMethod(
						"executeOnExecutor", Executor.class, Object[].class);
				Field field = android.os.AsyncTask.class
						.getField("THREAD_POOL_EXECUTOR");

				Object executor = field.get(null);
				method.invoke(this, executor, params);
			} catch (IllegalArgumentException e) {
				this.e = e;
			} catch (IllegalAccessException e) {
				this.e = e;
			} catch (InvocationTargetException e) {
				this.e = e;
			} catch (NoSuchMethodException e) {
				this.e = e;
			} catch (NoSuchFieldException e) {
				this.e = e;
			}
		} else {
			execute(params);
		}
	}

}
